package com.dream.service.recommender.hub.rec;

import com.alibaba.fastjson.JSONObject;
import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.service.procure.domain.enums.StockStatus;
import com.dream.service.product.domain.entity.SpuBase;
import com.dream.service.recommender.hub.util.CacheUtil;
import com.dream.service.recommender.hub.util.ParamUtil;
import com.dream.service.recommender.toolkits.cache.RedisCache;
import com.dream.service.recommender.toolkits.utils.ConfigUtil;
import com.dream.service.recommender.toolkits.utils.StringUtils;
import com.dream.service.search.api.SearchRecallService;
import com.dream.service.search.domain.entity.ProductRecallResult;
import com.dream.service.search.domain.enums.SortType;
import com.dream.service.search.domain.request.ProductSearchRequest;
import com.dream.service.wrapper.domain.entity.SPUData;
import com.dream.service.recommender.base.compare.WeightComparator;
import com.dream.service.recommender.base.impl.BaseRecommenderService;
import com.dream.service.recommender.domain.request.BaseRequest;
import com.dream.service.recommender.domain.request.FrontParam;
import com.dream.service.recommender.domain.response.RecommenderData;
import com.dream.service.recommender.domain.response.RecommenderItem;
import com.dream.service.recommender.domain.response.RecommenderSku;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 根据分类召回
 * Created by duxy on 2016/04/25.
 */
public class CategoryListRecommender extends BaseRecommenderService {



    private Logger logger = Logger.getLogger(CategoryListRecommender.class);

    private SearchRecallService searchRecallService;

    public SearchRecallService getSearchRecallService() {
        return searchRecallService;
    }

    @Autowired
    public void setSearchRecallService(SearchRecallService searchRecallService) {
        this.searchRecallService = searchRecallService;
    }

    // 获取商品数据倍数
    private int multiple = 5;

    // 失效时间间隔 (sec)
    private int residue_time_interval = Integer.parseInt(ConfigUtil.getPro("residue_time_interval_ca"));

    // 缓存
    private final String cacheKey = "rec_category_list_";

    // 缓存
    private RedisCache redisCache = RedisCache.getInstance();

    @Override
    public BaseResponse<RecommenderData> getRecommender(BaseRequest<FrontParam> frontParamBaseRequest) {
        long sTime = System.currentTimeMillis();
        BaseResponse<RecommenderData> recommenderResponse = new BaseResponse<RecommenderData>();
        try {
            if (frontParamBaseRequest == null || frontParamBaseRequest.getParam() == null || frontParamBaseRequest.getParam().getUser() == null) {
                return buildResult(recommenderResponse, false, ErrorCode.PARAM_ERROR.getCode(), ErrorCode.PARAM_ERROR.getError_msg(), null);
            }
            FrontParam frontParam = frontParamBaseRequest.getParam();
            int cid = ParamUtil.getCid(frontParam);
            int pagesize = ParamUtil.getPageSize(frontParam);
            int page = ParamUtil.getPage(frontParam);
//            System.out.println(page);
            Integer cityId = frontParam.getCityId();
            Map<Integer, Double> categoryWeightMap = new HashMap<Integer, Double>();
            if (cid > 0) {
                categoryWeightMap.put(cid, 1d);
            }
            //已经展示sku集合
            String pin = ParamUtil.getPin(frontParam);
            String uuid = ParamUtil.getUUid(frontParam);
            Map<String, String> extraValues = ParamUtil.getExtraValues(frontParam);

            //"1;2|a_b_c;3|d";
            String search_condition = "";
            int sort_state = 0;
            String condition[] = null;
 /*
        NEWEST_ASC(1),
        NEWEST_DESC(2),
        PRICE_ASC(3),
        PRICE_DESC(4),
        SALES_ASC(5),
        SALES_DESC(6);
        */
            boolean filterDesigner = false;
            if (extraValues != null && !extraValues.isEmpty() && extraValues.containsKey("sea")) {

                search_condition = extraValues.get("sea");

                condition = search_condition.split("\\|");

                if (condition.length == 1) {

                    String con_key = condition[0];

//                    if (con_key.equals("1"))
//                        sort_state = 2;
//                    else if (con_key.equals("2") || con_key.equals("5"))
//                        sort_state = 3;
//                    else if (con_key.equals("3"))
//                        sort_state = 6;
//                    else if (con_key.equals("4"))
//                        filterDesigner = true;
//                    else if (con_key.equals("6"))
//                        sort_state = 4;
                    try {
                        sort_state = Integer.parseInt(con_key.trim());
                    }catch (Exception e){}
                } else if (condition.length == 2) {

                    String con_key = condition[0];
                    String con_value = condition[1];

                    if (con_key.equals("1")) {
                        if (con_value.equals("1") || con_value.equals("a"))
                            sort_state = 1;
                        else sort_state = 2;
                    } else if (con_key.equals("2")) {
                        if (con_value.equals("1") || con_value.equals("d"))
                            sort_state = 4;
                        else sort_state = 3;
                    } else if (con_key.equals("3")) {
                        if (con_value.equals("1") || con_value.equals("a"))
                            sort_state = 5;
                        else sort_state = 6;
                    }
                }
//                System.out.println(sort_state);
            }


            Set<Long> existSpus = gatherExistSpuInfo(pin, uuid, cid, page, pagesize, sort_state);
            int skip = pagesize * (page - 1) - existSpus.size();
//            System.out.println(skip);
            if (skip < 0)
                skip = 0;
//            System.out.println(JSONObject.toJSONString(existSpus));
            List<ProductRecallResult> recallResults = gatherSearchRecallData(categoryWeightMap, null, pagesize * multiple, existSpus, skip, sort_state, filterDesigner);
//            System.out.println(JSONObject.toJSONString(recallResults));
            RecommenderData recommenderData = buildResult(recallResults, cid, page, existSpus, search_condition,cityId);

            recommenderResponse = buildResult(recommenderResponse, true, ErrorCode.OK.getCode(), "", recommenderData, 0, pagesize);


            Set<Long> spus = rebuildPositionInfo(recommenderResponse.getResult());
            backupExistSpuInfo(pin, uuid, spus, cid, sort_state);
            long usedTime = System.currentTimeMillis() - sTime;
            recommenderData.setLatency(usedTime);
            recommenderResponse.setLatency(usedTime);
            return recommenderResponse;
        } catch (Exception e) {
            logger.error("CategoryListRecommender===>getRecommender:::", e);
            return buildResult(recommenderResponse, false, ErrorCode.PROCESS_ERROR.getCode(), e.getMessage(), null);
        }
    }

    /**
     * 更新位置信息
     *
     * @param recommenderData
     * @return
     */
    public Set<Long> rebuildPositionInfo(RecommenderData recommenderData) {
        if (recommenderData == null || StringUtils.isEmpty(recommenderData.getList())) {
            return null;
        }
        List<RecommenderItem> items = recommenderData.getList();
        Set<Long> spus = new HashSet<Long>();
        int pos = 1;
        for (RecommenderItem recommenderItem : items) {
            recommenderItem.setPos(pos++);
            if (recommenderItem instanceof RecommenderSku) {
                try {
                    spus.add(((RecommenderSku) recommenderItem).getSpu());
                } catch (Exception e) {
                    logger.error("CategoryListRecommender===>rebuildPositionInfo:::", e);
                }
            }
        }
        return spus;
    }

    public Set<Long> gatherExistSpuInfo(String pin, String uuid, int category, int pageNum, int pageSize, int sort_state) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) {
            return Collections.emptySet();
        }
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
        String key = cacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));
        if (sort_state != 0) {
            key.concat(String.valueOf(sort_state));
        }
        if (pageNum == 1) {
            redisCache.delKey(key.getBytes());
            return Collections.emptySet();
        }
        Set<Long> spus = CacheUtil.getExistSpus(redisCache, key, (pageNum - 1) * pageSize);
//        System.out.println(JSONObject.toJSONString(spus));
        if (spus == null) {
            return Collections.emptySet();
        }
        return spus;
    }

    private List<ProductRecallResult> gatherSearchRecallData
            (Map<Integer, Double> categoryWeightMap, Map<Integer, Double> labelWeightMap, int limit, Set<
                    Long> existSpus, int skip, int sort_state, boolean filterDesigner) {

        ProductSearchRequest request = new ProductSearchRequest();
        if (filterDesigner)
            request.setDesignerId(-1);
        /*
        NEWEST_ASC(1),
        NEWEST_DESC(2),
        PRICE_ASC(3),
        PRICE_DESC(4),
        SALES_ASC(5),
        SALES_DESC(6);
        */

//        System.out.println(sort_state);
        request.setSortType(SortType.getEnumByState(sort_state));
//        if (sort_state == 1) {
//            request.setSortType(SortType.NEWEST_ASC);
//
//        } else if (sort_state == 2) {
//            request.setSortType(SortType.NEWEST_DESC);
//
//        } else if (sort_state == 3) {
//            request.setSortType(SortType.PRICE_ASC);
//
//        } else if (sort_state == 4) {
//            request.setSortType(SortType.PRICE_DESC);
//
//        } else if (sort_state == 5) {
//            request.setSortType(SortType.SALES_ASC);
//
//        } else if (sort_state == 6) {
//            request.setSortType(SortType.SALES_DESC);
//
//        }

        if (categoryWeightMap != null && !categoryWeightMap.isEmpty()) {
            request.setFrontCategoryWeightMap(categoryWeightMap);
        }
        if (labelWeightMap != null && !labelWeightMap.isEmpty()) {
            request.setLabelWeightMap(labelWeightMap);
        }
        request.setLimit(limit);
        request.setSkip(skip);

        if (existSpus != null && !existSpus.isEmpty()) {
            request.setExistKeys(existSpus);
        }
        try {
            if (searchRecallService == null) {
                return null;
            }
            BaseResponse<List<ProductRecallResult>> recallResponse = searchRecallService.productSearchRecall(request);
            if(logger.isDebugEnabled()){
                logger.debug("categoryListRecommender,request:"+ JSONObject.toJSONString(request)+"\tresponse:"+JSONObject.toJSONString(recallResponse));
            }
//            System.out.println(JSONObject.toJSONString(recallResponse));
            if (recallResponse.isSuccess()) {
                return recallResponse.getResult();
            }
        } catch (Exception e) {
            logger.error("CategoryListRecommender===>gatherSearchRecallData:::", e);
        }
        return null;
    }

    public void backupExistSpuInfo(String pin, String uuid, Set<Long> spus, int category, int sort_state) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) return;
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
        String key = cacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));
        if (sort_state != 0) {
            key.concat(String.valueOf(sort_state));
        }
        List<Long> cache = CacheUtil.backupCache(redisCache, key, spus, residue_time_interval, -1);
//        System.out.println("Backup Exist Spu :" + (cache == null ? "" : Arrays.toString(cache.toArray())));
    }

    /**
     * 封装结果
     *
     * @param recallResults
     * @param category
     * @return
     */
    private RecommenderData buildResult(List<ProductRecallResult> recallResults, int category, int page, Set<Long> existSpus, String search_condition,Integer cityId) {
        if (StringUtils.isEmpty(recallResults)) {
            return new RecommenderData();
        }
        RecommenderData<RecommenderSku> recommenderData = new RecommenderData<RecommenderSku>();
        List<RecommenderSku> recommenderSkus = new ArrayList<RecommenderSku>();
        recommenderData.setList(recommenderSkus);
        Set<Long> spus = new HashSet<Long>();
        for (ProductRecallResult recallResult : recallResults) {
            spus.add(recallResult.getSpu());
        }
        Map<Long, SPUData> spuDataMap = getBaseInfo(spus,cityId);
        if (spuDataMap == null || spuDataMap.isEmpty()) {
            return recommenderData;
        }
        for (ProductRecallResult recallResult : recallResults) {
            RecommenderSku recommenderSku = buildProduct(recallResult, spuDataMap.get(recallResult.getSpu()));
            if (recommenderSku != null) {
                recommenderSkus.add(recommenderSku);
            }
        }
        if (search_condition == null || search_condition.length() < 1)
            SortAndRank(recommenderData, spuDataMap);
//        SortAndRankPD(recommenderData, spuDataMap, page, existSpus);
        return recommenderData;
    }

    /**
     * 封装商品信息
     *
     * @param recallResult
     * @param spuData
     * @return
     */
    private RecommenderSku buildProduct(ProductRecallResult recallResult, SPUData spuData) {
        if (recallResult == null || spuData == null || spuData.getSpuBase() == null || spuData.getStockStatus() == StockStatus.NO || spuData.getSpuBase().getIsPutOn() == 0) {
            return null;
        }
        RecommenderSku recommenderSku = new RecommenderSku();
        SpuBase spuBase = spuData.getSpuBase();
        recommenderSku.setSpu(spuBase.getSpu());
        recommenderSku.setSale_type(spuBase.getSale_type());
        recommenderSku.setMain_sku(spuBase.getMain_sku());
        recommenderSku.setMain_title(spuBase.getMain_title());
        recommenderSku.setW(recallResult.getQuality_score());
        if (recallResult !=null && recallResult.getOther_image_paths() != null) {
            recommenderSku.setImage_paths(recallResult.getOther_image_paths());
        }
        if (!StringUtils.isEmpty(spuBase.getMain_image_url())) {
            recommenderSku.setMain_image_url(spuBase.getMain_image_url());
        } else {
            return null;
        }
        if (spuData.getSkuPrice() != null) {
            recommenderSku.setSkuPrice(spuData.getSkuPrice());
        } else {
            return null;
        }
        return recommenderSku;
    }

    /**
     * 穿插排序 (通过类目穿插)
     *
     * @param recommenderData
     * @param spuDataMap
     * @return
     */
    public RecommenderData SortAndRankPD(RecommenderData recommenderData, Map<Long, SPUData> spuDataMap, int page, Set<Long> existSpus) {
        if (recommenderData == null) {
            return recommenderData;
        }
        //System.out.println("page=" + page);
        //System.out.println(existSpus);
        List<RecommenderSku> recommenderSkus = recommenderData.getList();
        if (StringUtils.isEmpty(recommenderSkus)) {
            return recommenderData;
        }
        Map<Integer, List<RecommenderSku>> categoryItems = new HashMap<Integer, List<RecommenderSku>>();
        for (RecommenderSku recommenderSku : recommenderSkus) {//根据cid重组spu
            long spu = recommenderSku.getSpu();
            SPUData spuData = spuDataMap.get(spu);
            if (spuData == null) {//是不是多余的判断?
                continue;
            }
            SpuBase spuBase = spuData.getSpuBase();
            List<RecommenderSku> relSkus = categoryItems.get(spuBase.getCategory_id());
//            System.out.println(JSONObject.toJSONString(spuBase));
//            System.out.println(spuBase.getCategory_id());
//            System.out.println(spuBase.getFront_category_ids());
            if (relSkus == null) {
                relSkus = new ArrayList<RecommenderSku>();
                categoryItems.put(spuBase.getCategory_id(), relSkus);
            }
            relSkus.add(recommenderSku);
        }
        List<RecommenderSku> sortRecommenderItems = new ArrayList<RecommenderSku>();
        boolean loop = true;
        do {
            List<RecommenderSku> subRecommenderItems = new ArrayList<RecommenderSku>(categoryItems.size());

            Iterator<Map.Entry<Integer, List<RecommenderSku>>> entryiterator = categoryItems.entrySet().iterator();
            while (entryiterator.hasNext()) {
                Map.Entry<Integer, List<RecommenderSku>> productentry = entryiterator.next();
                List<RecommenderSku> productList = productentry.getValue();
                if (StringUtils.isEmpty(productList)) {
                    entryiterator.remove();
                    continue;
                }
                RecommenderSku recommenderSku = productList.remove(0);
//                recommenderSku.setW(Math.random());
//                if (page == 0 && existSpus.contains(recommenderSku.getSpu()))//对于已存在的spu降权0.5
//                {
//                    //System.out.println(recommenderSku.getSpu() + "降权");
//                    recommenderSku.setW(recommenderSku.getW() - 0.5);
//                }
                subRecommenderItems.add(recommenderSku);
            }

            sortRecommenderItems.addAll(subRecommenderItems);
            if (categoryItems.isEmpty()) {
                loop = false;
            }
            if (categoryItems.size() == 1) {
                Set<Integer> keys = categoryItems.keySet();
                Iterator<Integer> keyiterator = keys.iterator();
                while (keyiterator.hasNext()) {
                    Integer catid = keyiterator.next();
                    sortRecommenderItems.addAll(categoryItems.get(catid));
                }
                loop = false;
            }
        } while (loop);
        Collections.sort(sortRecommenderItems, new WeightComparator());
        recommenderData.setList(sortRecommenderItems);
        return recommenderData;
    }

}
